package Form;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import model.entities.Predictions;
import model.entities.StatisticStation;
import model.entities.Statistics;
import model.entities.WeatherStationCollection;
import DBConnection.PredictionsDB;
import DBConnection.StatisticStationDB;
import DBConnection.StatisticsDB;
import DBConnection.WeatherStationCollectionDB;

public class StatisticStationHandling {
	private String statisticStationID;
	private StatisticStation statisicStation = null;
	private List<Predictions> lPredictions = null;
	private List<Statistics> lStatistic = null;

	public List<Predictions> getlPredictions() {
		return lPredictions;
	}

	public void setlPredictions(List<Predictions> lPredictions) {
		this.lPredictions = lPredictions;
	}

	public String getStatisticStationID() {
		return statisticStationID;
	}

	public void setStatisticStationID(String statisticStationID) {
		this.statisticStationID = statisticStationID;
	}

	public StatisticStation getStatisicStation() {
		return statisicStation;
	}

	public void setStatisicStation(StatisticStation statisicStation) {
		this.statisicStation = statisicStation;
	}

	public List<Statistics> getlStatistic() {
		return lStatistic;
	}

	public void setlStatistic(List<Statistics> lStatistic) {
		this.lStatistic = lStatistic;
	}

	public StatisticStationHandling(String statisticStationID) {
		// Gan gia tri ID cua tram thong ke
		this.statisticStationID = statisticStationID;
		// Tim kiem tram co ID tuong ung roi gan vao object
		statisicStation = new StatisticStationDB().find(statisticStationID);
		// Lay het Statistic tu database bo vao mang
		lStatistic = new ArrayList<Statistics>();
		lPredictions = new ArrayList<Predictions>();

		List<Statistics> lTmp = new StatisticsDB().findAll();
		for (Statistics statistic : lTmp) {
			if (statistic.getSSID().equals(statisticStationID)) {
				lStatistic.add(statistic);
			}
		}

		// Lay het Prediction tu database bo vao mang
		List<Predictions> lTemp = new PredictionsDB().findAll();
		for (Predictions prediction : lTemp) {
			if (prediction.getSSID().equals(statisticStationID)) {
				lPredictions.add(prediction);
			}
		}

	}

	/*
	 * Ham nay dung de cap nhat lai lStatistic Lay tu csdl dem len class
	 */
	public void doUpdateListStatistic() {
		lStatistic = new StatisticsDB().findAll();
	}

	// Ham nay dung de lay ngay thang nam theo chuan hien tai
	public String getToDay() {
		Calendar cal = Calendar.getInstance();
		String today = "";
		today = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH) + 1)
				+ "-" + cal.get(Calendar.YEAR);
		return today;
	}

	public void ThongKe(String item, String type) {
		try {
			List<WeatherStationCollection> lWSC = new WeatherStationCollectionDB()
					.findAll();
			String today = getToDay();
			//Tao directory
			File fileDir = new File("Statistics");
			if (!fileDir.exists())
				fileDir.mkdirs();
			//Tao file
			File file = null;
			if (type.equals("Text")) {
				file = new File("Statistics/" + today + ".txt");
			} else if (type.equals("Word")) {
				file = new File("Statistics/" + today + ".doc");
			} else {
				file = new File("Statistics/" + today + ".xls");
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file, true);
			BufferedWriter bw = new BufferedWriter(fw);
			// Gia tri lon nhat cua thong ke
			double max = Double.MIN_VALUE;
			// Gia tri nho nhat cua thong ke
			double min = Double.MAX_VALUE;
			// Gia tri trung binh cua thong ke
			double AVG = 0;

			// Bat dau thong ke theo loai
			if (item.equals("Wind Speed")) {
				bw.write(today);
				bw.write("\r\n");
				for (WeatherStationCollection wSC : lWSC) {
					bw.write(wSC.getDate());
					bw.write("\t");
					bw.write(wSC.getWindSpeed().toString());
					bw.write(" km/h");
					bw.write("\r\n");
					// Lay gia tri lon nhat
					if (wSC.getWindSpeed() < min) {
						min = wSC.getWindSpeed();
					}
					// Lay gia tri nho nhat
					if (wSC.getWindSpeed() > max) {
						max = wSC.getWindSpeed();
					}
				}
				AVG = (max + min) / 2;
				bw.write("Max of wind speed\t\t" + Double.toString(max)
						+ " km/h\r\n");
				bw.write("Min of wind speed\t\t" + Double.toString(min)
						+ " km/h\r\n");
				bw.write("Average of wind speed\t\t" + Double.toString(AVG)
						+ " km/h\r\n");
				bw.write("\r\n");
				bw.close();
				String statis = "Max of wind speed\t\t" + Double.toString(max)
						+ " km/h\r\n";
				statis += "Min of wind speed\t\t" + Double.toString(min)
						+ " km/h\r\n";
				statis += "Average of wind speed\t\t" + Double.toString(AVG)
						+ " km/h\r\n";
				// Insert to database
				Statistics sta = new Statistics(getStatisticStationID(),
						statis, today);
				new StatisticsDB().add(sta);
				// cap nhat lai list Statistic sau khi tien doan
				doUpdateListStatistic();
			} else if (item.equals("Air Blast")) {
				bw.write(today);
				bw.write("\r\n");
				for (WeatherStationCollection wSC : lWSC) {
					bw.write(wSC.getDate());
					bw.write("\t");
					bw.write(wSC.getAirBlast().toString());
					bw.write(" m3");
					bw.write("\r\n");
					// Lay gia tri lon nhat
					if (wSC.getAirBlast() < min) {
						min = wSC.getAirBlast();
					}
					// Lay gia tri nho nhat
					if (wSC.getAirBlast() > max) {
						max = wSC.getAirBlast();
					}
				}
				AVG = (max + min) / 2;
				bw.write("Max of air blast\t\t" + Double.toString(max)
						+ " m3\r\n");
				bw.write("Min of air blast\t\t" + Double.toString(min)
						+ " m3\r\n");
				bw.write("Average of air blast\t\t" + Double.toString(AVG)
						+ " m3\r\n");
				bw.write("\r\n");
				bw.close();
				String statis = "Max of air blast\t\t" + Double.toString(max)
						+ " m3\r\n";
				statis += "Min of air blast\t\t" + Double.toString(min)
						+ " m3\r\n";
				statis += "Average of air blast\t" + Double.toString(AVG)
						+ " m3\r\n";
				// Insert to database
				Statistics sta = new Statistics(getStatisticStationID(),
						statis, today);
				new StatisticsDB().add(sta);
				// cap nhat lai list Statistic sau khi tien doan
				doUpdateListStatistic();
			} else if (item.equals("Rainfall in 24h")) {
				bw.write(today);
				bw.write("\r\n");
				for (WeatherStationCollection wSC : lWSC) {
					bw.write(wSC.getDate());
					bw.write("\t");
					bw.write(wSC.getRainfallIn24h().toString());
					bw.write(" mm");
					bw.write("\r\n");
					// Lay gia tri lon nhat
					if (wSC.getRainfallIn24h() < min) {
						min = wSC.getRainfallIn24h();
					}
					// Lay gia tri nho nhat
					if (wSC.getRainfallIn24h() > max) {
						max = wSC.getRainfallIn24h();
					}
				}
				AVG = (max + min) / 2;
				bw.write("Max of rainfall in 24h\t\t" + Double.toString(max)
						+ " mm\r\n");
				bw.write("Min of rainfall in 24h\t\t" + Double.toString(min)
						+ " mm\r\n");
				bw.write("Average of rainfall in 24h\t\t"
						+ Double.toString(AVG) + " mm\r\n");
				bw.write("\r\n");
				bw.close();
				String statis = "Max of rainfall in 24h\t\t"
						+ Double.toString(max) + " mm\r\n";
				statis += "Min of rainfall in 24h\t\t" + Double.toString(min)
						+ " mm\r\n";
				statis += "Average of rainfall in 24h\t" + Double.toString(AVG)
						+ " mm\r\n";
				// Insert to database
				Statistics sta = new Statistics(getStatisticStationID(),
						statis, today);
				new StatisticsDB().add(sta);
				// cap nhat lai list Statistic sau khi tien doan
				doUpdateListStatistic();
			} else if (item.equals("Air Moisture")) {
				bw.write(today);
				bw.write("\r\n");
				for (WeatherStationCollection wSC : lWSC) {
					bw.write(wSC.getDate());
					bw.write("\t");
					bw.write(wSC.getAirMoisture().toString());
					bw.write(" ktm");
					bw.write("\r\n");
					// Lay gia tri lon nhat
					if (wSC.getAirMoisture() < min) {
						min = wSC.getAirMoisture();
					}
					// Lay gia tri nho nhat
					if (wSC.getAirMoisture() > max) {
						max = wSC.getAirMoisture();
					}
				}
				AVG = (max + min) / 2;
				bw.write("Max of air moisture\t\t" + Double.toString(max)
						+ " ktm\r\n");
				bw.write("Min of air moisture\t\t" + Double.toString(min)
						+ " ktm\r\n");
				bw.write("Average of air moisture\t\t" + Double.toString(AVG)
						+ " ktm\r\n");
				bw.write("\r\n");
				bw.close();
				String statis = "Max of air moisture\t\t"
						+ Double.toString(max) + " ktm\r\n";
				statis += "Min of air moisture\t\t" + Double.toString(min)
						+ " ktm\r\n";
				statis += "Average of air moisture\t" + Double.toString(AVG)
						+ " ktm\r\n";
				// Insert to database
				Statistics sta = new Statistics(getStatisticStationID(),
						statis, today);
				new StatisticsDB().add(sta);
				// cap nhat lai list Statistic sau khi tien doan
				doUpdateListStatistic();
			} else if (item.equals("Ground Moisture")) {
				bw.write(today);
				bw.write("\r\n");
				for (WeatherStationCollection wSC : lWSC) {
					bw.write(wSC.getDate());
					bw.write("\t");
					bw.write(wSC.getGroundMoisture().toString());
					bw.write(" kmt");
					bw.write("\r\n");
					// Lay gia tri lon nhat
					if (wSC.getGroundMoisture() < min) {
						min = wSC.getGroundMoisture();
					}
					// Lay gia tri nho nhat
					if (wSC.getGroundMoisture() > max) {
						max = wSC.getGroundMoisture();
					}
				}
				AVG = (max + min) / 2;
				bw.write("Max of ground moisture\t\t" + Double.toString(max)
						+ " kmt\r\n");
				bw.write("Min of ground moisture\t\t" + Double.toString(min)
						+ " kmt\r\n");
				bw.write("Average of ground moisture\t\t"
						+ Double.toString(AVG) + " kmt\r\n");
				bw.write("\r\n");
				bw.close();
				String statis = "Max of ground moisture\t\t"
						+ Double.toString(max) + " kmt\r\n";
				statis += "Min of ground moisture\t\t" + Double.toString(min)
						+ " kmt\r\n";
				statis += "Average of ground moisture\t" + Double.toString(AVG)
						+ " kmt\r\n";
				// Insert to database
				Statistics sta = new Statistics(getStatisticStationID(),
						statis, today);
				new StatisticsDB().add(sta);
				// cap nhat lai list Statistic sau khi tien doan
				doUpdateListStatistic();
			} else if (item.equals("Air Pressure")) {
				bw.write(today);
				bw.write("\r\n");
				for (WeatherStationCollection wSC : lWSC) {
					bw.write(wSC.getDate());
					bw.write("\t");
					bw.write(wSC.getAirPressure().toString());
					bw.write(" atm");
					bw.write("\r\n");
					// Lay gia tri lon nhat
					if (wSC.getAirPressure() < min) {
						min = wSC.getAirPressure();
					}
					// Lay gia tri nho nhat
					if (wSC.getAirPressure() > max) {
						max = wSC.getAirPressure();
					}
				}
				AVG = (max + min) / 2;
				bw.write("Max of air pressure\t\t" + Double.toString(max)
						+ " atm\r\n");
				bw.write("Min of air pressure\t\t" + Double.toString(min)
						+ " atm\r\n");
				bw.write("Average of air pressure\t\t" + Double.toString(AVG)
						+ " atm\r\n");
				bw.write("\r\n");
				bw.close();
				String statis = "Max of air pressure\t\t"
						+ Double.toString(max) + " atm\r\n";
				statis += "Min of air pressure\t\t" + Double.toString(min)
						+ " atm\r\n";
				statis += "Average of air pressure\t" + Double.toString(AVG)
						+ " atm\r\n";
				// Insert to database
				Statistics sta = new Statistics(getStatisticStationID(),
						statis, today);
				new StatisticsDB().add(sta);
				// cap nhat lai list Statistic sau khi tien doan
				doUpdateListStatistic();
			} else {
				// Dang hoan thien
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/*
	 * Ham nay dung de lay noi dung cua Index duoc truyen vao trong list
	 * Statistic
	 */
	public String getStatisticContent(String value) {
		try {
			// Cat chuoi ra de lay index
			String[] tmp = value.split("\\ ");
			// Lay noi dung ung voi index
			String valueResult = lStatistic.get(Integer.parseInt(tmp[1]) - 1)
					.getStatisic();
			// Lay ngay thang
			valueResult += lStatistic.get(Integer.parseInt(tmp[1]) - 1)
					.getDate();
			return valueResult;
		} catch (Exception e) {
			return null;
		}
	}

	/* Ham nay dung de Tien doan cac hoat dong lien quan den nang mua gio... */
	public void TienDoan(String prediction, String type) {
		try {
			// Lay ngay hien tai lam ten file
			String today = getToDay();
			//Tao directory
			File fileDir = new File("Predictions");
			if (!fileDir.exists())
				fileDir.mkdirs();
			//Tao file
			File file = null;
			if (type.equals("Text")) {
				file = new File("Predictions/" + today + ".txt");
			} else if (type.equals("Word")) {
				file = new File("Predictions/" + today + ".doc");
			} else {
				file = new File("Predictions/" + today + ".xls");
			}
			if (!file.exists())
				file.createNewFile();
			FileWriter fw = new FileWriter(file, true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(today);
			bw.write("\r\n");
			bw.write(prediction);
			bw.write("\r\n\r\n");
			bw.close();
			// Insert to database Predictions table
			Predictions pre = new Predictions(getStatisticStationID(),
					prediction, today);
			new PredictionsDB().add(pre);
			// Cap nhat lai listPrediction sau khi tien doan
			doUpdateListPrediction();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/*
	 * Ham nay dung de lay noi dung cua Index duoc truyen vao trong list
	 * Prediction
	 */
	public String getPredictionContent(String value) {
		try {
			// Cat chuoi ra de lay index
			String[] tmp = value.split("\\ ");
			// Lay noi dung ung voi index
			String valueResult = lPredictions.get(Integer.parseInt(tmp[1]) - 1)
					.getPrediction();
			// Xuong dong
			valueResult += "\r\n";
			// Lay ngay thang
			valueResult += lPredictions.get(Integer.parseInt(tmp[1]) - 1)
					.getDate();
			return valueResult;
		} catch (Exception e) {
			return null;
		}
	}

	private void doUpdateListPrediction() {
		lPredictions = new PredictionsDB().findAll();

	}
}
